<template>
	<!-- <view class="" style="padding:0 40rpx;" v-if='loading'>
		<up-skeleton rows="3" :rowsWidth="['100%', '100%', '100%']" :rowsHeight="['100rpx', '100rpx', '100rpx']"
			loading></up-skeleton>
	</view> -->
	<view>
		<view class="device-list-empty" v-if="deviceListFlag">
			<!-- <view class=""> 您还没有绑定设备 </view> -->
			<image src="@/static/empty.png" mode="" style="width: 200rpx; height: 200rpx"></image>
		</view>
		<view :class="showBtn ? 'device-main-padding' : 'device-main'" v-if="deviceList.length" @scroll="onScroll">
			<view class="devide-choose">
				<view class="devide-choose-all" @click="allCheckedDevice">
					<text v-if="showCheckbox && showAllCheck">选择全部</text>
					<text v-if="showCheckbox && !showAllCheck">取消全选</text>
				</view>
				<view class="devide-choose-action" @click="chooseDevice" v-show="!showCheckbox">
					<text>选择</text>
				</view>
				<view class="devide-choose-action" @click="cancelSet" v-show="showCheckbox">
					<text>取消</text>
				</view>
			</view>

			<view class="device-list" v-for="(item, index) in deviceList || []" :key="index">
				<swipe-delete @delete.stop="deleteItem(item)" @drag-start.stop="onDragStart" ref="swipeRefs"
					@longPress.stop="longPressItem(item)">
					<view class="device-list-item" v-if="item.devOnline == '1'||item.devOnline == '2'"
						@click="selectDevice(item)">
						<view class="device-list-item-icon">
							<image src="@/static/icons/dcn.jpg" mode="" style="width: 120rpx; height: 120rpx"
								v-if="item.devOnline == '1' ||item.devOnline == '2'">
							</image>
							<image src="@/static/icons/dcnOff.jpg" mode="" style="width: 120rpx; height: 120rpx" v-else>
							</image>
						</view>
						<view class="device-list-item-main">
							<view class="device-list-item-name">
								<text>{{ item.devName }}</text>
							</view>
							<view class="device-list-item-set">
								<view class="device-list-item-set-item" v-if="item.devOnline == '1'">
									<up-badge type="success" :isDot="true"></up-badge>
								</view>

								<view class="device-list-item-set-item" v-else="item.devOnline == '2'">
									<up-badge type="primary" :isDot="true"></up-badge>
								</view>
								<view class="device-list-item-set-item">
									<text v-if="item.devOnline == '1'" style="color: #5ac725">在线</text>
									<text v-else="item.devOnline == '2'">状态获取中</text>
								</view>
								<view :class="
                    item.devOnOffName == '开机'
                      ? 'device-list-item-set-item'
                      : 'device-list-item-set-item-close'
                  ">
									<text>{{ item.devTemp1}}</text>
								</view>
								<view :class="
                    item.devOnOffName == '开机'
                      ? 'device-list-item-set-item'
                      : 'device-list-item-set-item-close'
                  ">
									<text>{{ item.devOnOffName }}</text>
								</view>

								<view :class="
                    item.devOnOffName == '开机'
                      ? 'device-list-item-set-item'
                      : 'device-list-item-set-item-close'
                  ">
								</view>
								<view :class="
                    item.devOnOffName == '开机'
                      ? 'device-list-item-set-item'
                      : 'device-list-item-set-item-close'
                  ">
									<text :class="
                      item.devOnOffName == '开机'
                        ? 'device-list-item-set-item'
                        : 'device-list-item-set-item-close'
                    " v-if="item.devOnOffName == '开机'">{{
                      getLabel(`sys_devMode_${item.devType}`, item.devRunMode)
                    }}</text>
									<text :class="
                      item.devOnOffName == '开机'
                        ? 'device-list-item-set-item'
                        : 'device-list-item-set-item-close'
                    " v-if="item.devOnOffName == '开机'">{{ item.devHeating == "0" ? "" : "启动" }}</text>
								</view>
							</view>
						</view>
						<view class="device-list-item-checkbox" v-if="showCheckbox">
							<up-checkbox usedAlone v-model:checked="item.choose" @change.stop="checkedDevice(item)" />
						</view>
					</view>
					<!-- 网关 -->
					<view class="device-list-item" v-else-if="item.isGateway == 'Y'" @click.stop="selectDevice(item)">
						<view class="device-list-item-icon">
							<image src="@/static/icons/gateIcon.png" mode="" style="width: 110rpx; height: 100rpx">
							</image>
						</view>
						<view class="device-list-item-main">
							<view class="device-list-item-name">
								<text>{{ item.devName }}</text>
							</view>
							<view class="device-list-item-set">
								<view class="device-list-item-set-item" style="font-size: 19rpx; padding-right: 8rpx">
									本地地址{{ item.gwAddr }}
								</view>
								<view class="device-list-item-set-item" style="font-size: 19rpx; padding-right: 8rpx">
									无线信道{{ item.gwChannel }}
								</view>
								<view class="device-list-item-set-item" style="font-size: 19rpx; padding-right: 8rpx">
									带载数量{{ item.gwDevCnt }}
								</view>
								<view class="device-list-item-set-item" style="font-size: 19rpx; padding-right: 8rpx">
									在线数量{{ item.devOnlineCnt }}
								</view>
								<view class="device-list-item-set-item" style="font-size: 19rpx; padding-right: 8rpx">
									离线数量{{ item.devOfflineCnt }}
								</view>
							</view>
						</view>
					</view>

					<view class="device-list-item" v-if="item.devOnline == '0'" @click.stop="selectDevice(item)">
						<view class="device-list-item-icon">
							<image src="@/static/icons/dcnOff.jpg" mode="" style="width: 110rpx; height: 100rpx">
							</image>
						</view>
						<view class="device-list-item-main">
							<view class="device-list-item-name">
								<text>{{ item.devName }}</text>
							</view>
							<view class="device-list-item-set">
								<view class="device-list-item-set-item">
									<up-badge type="error" :isDot="true"></up-badge>
								</view>
								<view class="device-list-item-set-item">
									<text style="color: #000">离线</text>
								</view>
							</view>
						</view>
						<!-- <view class="device-offLine" v-else>
							该设备处于离线状态,无法操作
						</view> -->
					</view>
				</swipe-delete>
			</view>
		</view>
	</view>
	<view class="">
		<up-modal :show="showLongPress" :showConfirmButton="true" :showCancelButton="true" :closeOnClickOverlay="true"
			:buttonReverse="true" @close="closeModal" @cancel="closeModal" @confirm="confirmModal"
			confirmColor="#25afe5">
			<view class="slot-content">
				<view class="">
					<view class="edit-device-name" style="display: flex; line-height: 40rpx; font-size: 26rpx"
						v-if="longPressData">
						<view style="width: 120rpx; font-weight: 500">序列号:</view>
						{{ longPressData.equipNo }}
					</view>
					<view style="display: flex; margin-top: 20rpx">
						<view class="" style="width: 120rpx; font-size: 24rpx; line-height: 70rpx">
							设备名称:
						</view>
						<view class="edit-device-name-input">
							<up-input v-model="newDevName" type="text" border="surround" />
							<view class="edit-device-name-input-error" v-show="newDevName == ''">
								设备名称不能为空
							</view>
						</view>
					</view>
				</view>
			</view>
		</up-modal>
		<view :class="showBtn ? 'control-btn' : 'control-btn-none'">
			<view class="" style="width: 30vw">
				<up-button text="取消" shape="circle" size="small" @click="cancelSet"></up-button>
			</view>
			<view class="" style="width: 30vw">
				<up-button type="primary" text="批量控制" shape="circle" @click="handlerControl" size="small"></up-button>
			</view>
		</view>
		<up-popup v-model:show="showSet" @close="cancelSet">
			<view class="set-popup">
				<view class="set-popup-column">
					<view class="set-popup-column-label"> 开关状态 </view>
					<view class="">
						<up-select v-model="FlagId" :label="FlagId" ref="flagOpotion">
							<template #options>
								<view class="custom-option" v-for="(opt, idx) in FlagList" :key="idx"
									@click="selectItemFlag(opt)">
									{{ opt.label }}
								</view>
							</template></up-select>
					</view>
					<view class="">
						<up-button type="primary" size="small" text="确认" @click="handlerFlag"></up-button>
					</view>
				</view>
				<view class="set-popup-column" v-if="sameType">
					<view class="set-popup-column-label"> 设定温度 </view>
					<view class="">
						<up-select ref="tempOption" v-model="tempId" :label="tempId">
							<template #options>
								<scroll-view class="option-scroll" scroll-y>
									<!-- 遍历所有选项，放在scroll-view内部 -->
									<view class="custom-option" v-for="(opt, idx) in tempList" :key="idx"
										@click="handlerTempCheck(opt)">
										{{ opt.label }}
									</view>
								</scroll-view>
							</template>
						</up-select>
					</view>
					<view class="">
						<up-button type="primary" size="small" text="确认" @click="handerTemp"></up-button>
					</view>
				</view>
				<view class="set-popup-column" v-if="sameType">
					<view class="set-popup-column-label"> 运行模式 </view>
					<view class="">
						<up-select v-model="modeId" :label="modeId" ref="modeOpotion">
							<template #options>
								<view class="custom-option" v-for="(opt, idx) in modeList" :key="idx"
									@click="selectItemMode(opt)">
									{{ opt.label }}
								</view>
							</template></up-select>
					</view>
					<view class="">
						<up-button type="primary" size="small" text="确认" @click="handlerMode"></up-button>
					</view>
				</view>
				<view class="set-popup-column" v-if="sameType">
					<view class="set-popup-column-label"> {{identity?'网络锁':'童锁模式'}} </view>
					<view class="">
						<up-select v-model="lockId" :label="lockId" ref="lockOpotion">
							<template #options>
								<view class="custom-option" v-for="(opt, idx) in ChildLock" :key="idx"
									@click="selectItemLock(opt)">
									{{ opt.label }}
								</view>
							</template></up-select>
					</view>
					<view class="">
						<up-button type="primary" size="small" text="确认" @click="handlerLock"></up-button>
					</view>
				</view>
				<view class="set-popup-column" v-if="sameType">
					<view class="set-popup-column-label"> 智能配置</view>
					<view class="">
						<!-- 	<up-select v-model="lockId" :label="lockId" ref="lockOpotion">
							<template #options>
								<view class="custom-option" v-for="(opt, idx) in ChildLock" :key="idx"
									@click="selectItemLock(opt)">
									{{ opt.label }}
								</view>
							</template></up-select> -->
					</view>
					<view class="">
						<up-button type="primary" size="small" text="配置" :plain="true"
							@click="handlerController"></up-button>
					</view>
				</view>
				<view style="font-size: 22rpx; margin-top: 30rpx" v-if="sameType">
					<text style="color: red">注:</text>
					<text style="color: #777">设定温度超出可设置范围时，温控器的目标温度不会更改。</text>
				</view>
			</view>
		</up-popup>
		<up-popup :show="intelligenceShow" mode="center" round="10">
			<intelligence-set :checkList="deviceCheckbox" @closePopup="handleIntelligenceClose"></intelligence-set>
		</up-popup>

	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted,
		onUnmounted,
		nextTick,
		getCurrentInstance,
		watch,
	} from "vue";
	import {
		onLoad,
		onShow,
		onHide,
		onPullDownRefresh
	} from "@dcloudio/uni-app";
	import {
		useUserStore
	} from "@/store/user";
	import {
		dictDataStore
	} from "@/store/dict.js";

	// 获取store实例
	const userStore = useUserStore();
	const badgeType = ref("success");
	const showLongPress = ref(false);
	const deleteIndex = ref(false);
	const showCheckbox = ref(false);
	const showAllCheck = ref(true);
	const showSet = ref(false);
	const showBtn = ref(false);
	const FlagId = ref("");
	const tempId = ref("");
	const tempOption = ref(null);
	const modeOpotion = ref(null);
	const flagOpotion = ref(null);
	const lockOpotion = ref(null);
	const modeId = ref("");
	const newDevName = ref("");
	const longPressData = ref(null);
	const deviceLongId = ref("");
	const pageNum = ref(1);
	const pageSize = ref(30);
	const hasMore = ref(true); // 是否还有更多数据
	const loading = ref(true); // 是否正在加载中
	const isRefreshing = ref(false); // 是否正在下拉刷新
	const sameType = ref(false); // 判断批量控制是否同一类型设
	const FlagList = ref([]);
	const ChildLock = ref([]);
	const lockId = ref("");
	const dict = dictDataStore();
	const tempList = ref([]);
	const modeList = ref([]);
	const searchValue = ref("");
	const editLongItem = ref({});
	// 保存所有子组件的引用
	const swipeRefs = ref([]);
	const deviceCheckbox = ref([]);
	const deviceList = ref([]);
	const deviceListFlag = ref(false)
	const refreshTimer = ref(null);
	const openId = ref("");
	const identity = ref(false); //是否为管理员
	const intelligenceShow = ref(false)

	const props = defineProps({
		setSearch: {
			type: String,
			default: "",
		},
		itemId: {
			type: String,
			default: "",
		},
	});
	onHide(() => {
		stopAutoRefresh();
		deviceListFlag.value = false;
	});
	const handleSearch = (searchText) => {
		// uni.showLoading()
		searchValue.value = searchText;
		pageNum.value = 1;
		hasMore.value = true;
		isRefreshing.value = true;
		getList();
	};

	watch(
		() => props.setSearch,
		(newVal) => {
			if (newVal !== undefined && newVal !== null) {
				handleSearch(newVal);
			}
		}
	);

	const getLabel = (type, value) => {
		let arr = uni.getStorageSync(type) || [];
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].dictValue == value) {
				return arr[i].dictLabel;
			}
		}
		return "";
	};
	//留给父组件的刷新
	const onPullDownReload = () => {

		deleteIndex.value = false;
		showLongPress.value = false;
		pageNum.value = 1;
		// 下拉刷新时重置参数
		hasMore.value = true; // 重置是否有更多数据
		isRefreshing.value = true; // 标记为下拉刷新
		openId.value = uni.getStorageSync("openid") || false;
		identity.value = uni.getStorageSync("identity") || false;
		if (identity.value) {
			// 管理员身份
			let arr = (identity.value = uni.getStorageSync("sys_devKey_lock"));
			ChildLock.value = arr.map((item) => {
				return {
					label: item.dictLabel,
					value: item.dictValue,
				};
			});
		} else {
			// 普通用户身份
			ChildLock.value = [{
					label: "解锁",
					value: "0",
				},
				{
					label: "上锁",
					value: "1",
				},
			];
		}
		if (openId.value) {
			getList();
		} else {
			deviceListFlag.value = true;
		}
	};
	const getList1 = async () => {
		let data = {
			searchValue: searchValue.value || "",
		};
		let url = "";
		//管理员和用户的路径动态
		if (identity.value) {
			url = "/wechat/getDevListByItemId";
			data.itemId = userStore.getItemId();
		} else {
			url = "/wechat/getBindDevList";
		}
		try {
			let res = await uni.$u.http.post(url, data);

			if (pageNum.value == 1) {
				// 下拉刷新：直接替换数据

				uni.stopPullDownRefresh();
				setTimeout(() => {
					if (res.data) {
						// 保存当前选中状态
						const selectedDevices = deviceCheckbox.value.map(
							(item) => item.equipNo
						);
						deviceList.value = res.data;
						if (deviceList.value.length) {
							deviceList.value.forEach((item) => {
								if (item.devTemp1) {
									if (item.devTemp1.includes('32768') || item.devTemp1
										.includes(
											'32767')) {
										item.devTemp1 = '探头故障'
									} else {
										item.devTemp1 = item.devTemp1 + '℃'
									}
								}

							})
						}
						// 恢复选中状态
						if (showCheckbox.value) {
							deviceList.value.forEach((device) => {
								if (selectedDevices.includes(device.equipNo)) {
									device.choose = true;
									// 确保deviceCheckbox中包含该设备
									const exists = deviceCheckbox.value.some(
										(item) => item.equipNo === device.equipNo
									);
									if (!exists) {
										deviceCheckbox.value.push(device);
									}
								} else {
									device.choose = false;
								}
							});
						}
					}

					// loading.value = false;
					setTimeout(() => {
						deviceListFlag.value = !res.data.length;
					}, 200);
					isRefreshing.value = false; // 重置刷新状态
				}, 300);
			} else if (isRefreshing.value) {
				// 下拉刷新：直接替换数据
				if (res.data) {
					deviceList.value = res.data;
				}
				// setTimeout(() => {
				// 	deviceListFlag.value = !res.data.length
				// }, 200)
				isRefreshing.value = false;
				uni.stopPullDownRefresh(); // 停止下拉刷新动画
				uni.hideLoading();
			}
			hasMore.value = res.data.length >= pageSize.value;
		} finally {
			// loading.value = false;
			isRefreshing.value = false; // 重置刷新状态
		}
	};
	const getList = async () => {
		deviceListFlag.value = false;
		// 如果正在加载或没有更多数据，直接返回
		if (!hasMore.value && !isRefreshing.value) {
			isRefreshing.value = false; // 确保状态重置
		}
		stopAutoRefresh();
		loading.value = true; // 开始加载
		// deviceList.value = []
		getList1();
		loading.value = !deviceList.value;
		setTimeout(() => {
			startAutoRefresh();
		}, 1000);
	};

	// 添加启动定时刷新的方法
	const startAutoRefresh = () => {
		// 清除已存在的定时器
		stopAutoRefresh();
		// 设置20秒定时刷新
		refreshTimer.value = setInterval(() => {
			// 只在第一页且不在刷新状态时执行自动刷新
			isRefreshing.value = true;
			getList1();
		}, 5000); // 5秒
	};

	// 添加停止定时刷新的方法
	const stopAutoRefresh = () => {
		if (refreshTimer.value) {
			clearInterval(refreshTimer.value);
			refreshTimer.value = null;
		}
	};

	// 删除项目
	const deleteItem = (data) => {
		deleteIndex.value = true;
		// 添加删除确认逻辑（可选）
		uni.showModal({
			title: "确认删除",
			content: `确定要删除设备${data.devName}吗？`,
			success: (res) => {
				if (res.confirm) {
					let param = {
						equipNo: data.equipNo,
						devId: data.id,
					};
					let url = "";
					//管理员和用户的路径动态
					if (identity.value) {
						param.itemId = userStore.getItemId();
						if (data.isGateway == "Y") {
							url = "wechat/removeGwFromItem";
						} else {
							url = "/wechat/removeDevFromItem";
						}
					} else {
						if (data.isGateway == "Y") {
							url = "/wechat/removeBindGw";
						} else {
							url = "/wechat/removeBindDev";
						}
					}
					uni.$u.http.post(url, param).then((res) => {
						if (res.success) {
							uni.showToast({
								title: "设备删除成功",
								icon: "success",
							});
							setTimeout(() => {
								getList();
							}, 1500);
						}
					});
				} else {
					deleteIndex.value = false;
				}
			},
			fail: () => {
				deleteIndex.value = false;
			},
		});
	};

	// 点击容器时隐藏所有删除按钮
	const onContainerClick = () => {
		swipeRefs.value.forEach((ref) => {
			ref?.hideDeleteBtn?.();
		});
	};

	// 当某个组件开始滑动时，隐藏其他组件的删除按钮
	const onDragStart = (index) => {
		swipeRefs.value.forEach((ref, i) => {
			if (i !== index) {
				ref?.hideDeleteBtn?.();
			}
		});
	};

	// 选择设备
	const selectDevice = (device) => {
		if (showCheckbox.value) return;
		if (deleteIndex.value) return;
		if (showLongPress.value) return;
		if (!showLongPress.value && device.devOnline == "0") {
			uni.showToast({
				title: "设备离线状态，无法操作",
				icon: "none",
			});
			return;
		}
		if (device.isGateway == "Y") {
			uni.navigateTo({
				url: `/Device/SuperGateway/SuperGateway?id=${encodeURIComponent(
        device.id
      )}`,
			});
		} else {
			uni.navigateTo({
				url: `/Device/setDevide/setDevide?id=${encodeURIComponent(
        device.id
      )}&&devName=${encodeURIComponent(device.devName)}`,
			});
		}
		userStore.updAdminType(false);
	};
	const handlerControl = async () => {
		let res = areAllDevTypesSame(deviceCheckbox.value);
		sameType.value = res;
		if (sameType.value) {
			const devType = deviceCheckbox.value[0].devType;
			modeList.value = uni
				.getStorageSync(`sys_devMode_${devType}`)
				.map((item) => ({
					label: item.dictLabel,
					value: Number(item.dictValue),
				}));

			tempList.value = [];
			for (let i = 5; i <= 85; i++) {
				tempList.value.push({
					label: `${i}℃`, // 显示带单位
					value: i,
				});
			}
		}
		FlagList.value = uni.getStorageSync("sys_switch_status").map((item) => ({
			label: item.dictLabel,
			value: Number(item.dictValue),
		}));
		await nextTick(); // 等待 DOM 更新
		if (deviceCheckbox.value.length == 1) {
			modeId.value = modeList.value.find(
				(obj) => obj.value == deviceCheckbox.value[0].devRunMode
			)?.label;
			FlagId.value = FlagList.value.find(
				(obj) => obj.value == deviceCheckbox.value[0].devOnOff
			)?.label;
			tempId.value = tempList.value.find(
				(obj) => obj.value == deviceCheckbox.value[0].devTempset
			)?.label || "20℃";
			if (identity.value) {
				lockId.value = ChildLock.value.find(
					(obj) => obj.value == deviceCheckbox.value[0].devKeyLock
				)?.label;
			} else {
				lockId.value = ChildLock.value.find(
					(obj) => obj.value == deviceCheckbox.value[0].devchildLock
				)?.label;
			}


		} else {
			modeId.value = modeList.value[0]?.label;
			FlagId.value = FlagList.value.find((obj) => obj.label == "开机")?.label;
			tempId.value = "20℃";
			lockId.value = "解锁";
		}

		showBtn.value = false;
		showSet.value = true;

	};

	// 判断批量控制是否是同一类型设备
	const areAllDevTypesSame = (arr) => {
		// 处理空数组情况（根据需求决定返回true还是false，这里默认返回true）
		if (arr.length === 0) return;

		// 取第一个对象的devType作为基准
		const firstDevType = arr[0].devType;

		// 遍历数组，对比每个对象的devType是否与基准一致
		return arr.every((item) => item.devType === firstDevType);
	};
	// 长按
	const longPressItem = (data) => {
		// 离线状态直接返回，不弹出修改弹窗
		// if (data.devOnline == "0") return;
		longPressData.value = data;
		newDevName.value = data.devName;
		showLongPress.value = true;
		deviceLongId.value = data.id;
		editLongItem.value = data;
	};

	// 弹窗关闭
	const closeModal = () => {
		showLongPress.value = false;
	};

	// 弹窗确认按钮
	const confirmModal = () => {
		if (newDevName.value == "") {
			return;
		}
		let param = {
			devName: newDevName.value,
			devId: deviceLongId.value,
			equipNo: longPressData.value.equipNo,
		};
		let url = "";
		//管理员和用户的路径动态
		if (identity.value) {
			param.itemId = userStore.getItemId();
			if (editLongItem.value.isGateway == "Y") {
				url = "wechat/editGwNameForItem";
			} else {
				url = "/wechat/editDevNameForItem";
				param.equipNo = longPressData.value.equipNo;
			}
			param.itemId = userStore.getItemId();
		} else {
			if (editLongItem.value.isGateway == "Y") {
				url = "/wechat/editGwName";
			} else {
				url = "/wechat/editDevName";
				param.equipNo = longPressData.value.equipNo;
			}
		}

		uni.$u.http.post(url, param).then((res) => {
			if (res.success) {
				uni.showToast({
					title: "修改成功",
					icon: "success",
				});
				// 只更新当前设备，而不是刷新整个列表
				const index = deviceList.value.findIndex(
					(item) => item.equipNo === longPressData.value.equipNo
				);

				if (index !== -1) {
					// 使用 splice 确保响应式更新
					const updatedItem = {
						...deviceList.value[index],
						devName: newDevName.value,
					};
					deviceList.value.splice(index, 1, updatedItem);
				}
				longPressData.value = null;
				showLongPress.value = false;
			}
		});
	};

	// 开启设备设置
	const chooseDevice = () => {
		deviceList.value.forEach((item) => {
			item.choose = false;
		});
		showCheckbox.value = !showCheckbox.value;
		showAllCheck.value = true;
	};
	// 多选设备
	const checkedDevice = (item) => {
		item.choose = !item.choose;
		// 选中：添加到数组（避免重复添加）
		if (item.choose) {
			const isExist = deviceCheckbox.value.some(
				(checkboxItem) => checkboxItem.equipNo === item.equipNo
			);
			if (!isExist) {
				deviceCheckbox.value.push(item);
			}
		}
		// 取消选中：从数组中删除
		else {
			const index = deviceCheckbox.value.findIndex(
				(checkboxItem) => checkboxItem.equipNo === item.equipNo
			);
			if (index !== -1) {
				deviceCheckbox.value.splice(index, 1); // 传入索引删除
			}
		}
		if (deviceCheckbox.value.length > 0) {
			showBtn.value = true;
		}
	};
	// 全选设备
	const allCheckedDevice = () => {
		showAllCheck.value = !showAllCheck.value;
		if (showAllCheck.value) {
			showAllCheck.value;
			showBtn.value = false;
			deviceCheckbox.value = [];
			deviceList.value.forEach((item) => {
				item.choose = false;
			});
		} else {
			showBtn.value = true;
			deviceCheckbox.value = [...deviceList.value.filter(item => item.devOnline !==
				"0")]; // 复制所有设备到选中数组
			deviceList.value.forEach((item) => {
				item.choose = true;
			});
		}
		//   showAllCheck.value = !showAllCheck.value;
		//   if (showAllCheck.value) {
		//     showBtn.value = false;
		//   } else {
		//     showBtn.value = true;
		//   }
		//   if (deviceList.value.every((item) => item.choose === true)) {
		//     deviceList.value.forEach((item) => {
		//       item.choose = false;
		//     });
		//   } else {
		//     deviceList.value.forEach((item) => {
		//       item.choose = true;
		//     });
		//   }
	};
	// 取消批量设置
	const cancelSet = () => {
		showBtn.value = false;
		showCheckbox.value = false;
		deviceCheckbox.value = [];
		FlagId.value = "";
		modeId.value = "";
		tempId.value = "";
	};
	// 批量设置提取equipNo的新数组
	const getEquipNoArray = (objects) => {
		return objects.map((obj) => obj.id);
	};
	// 设置开关
	const selectItemFlag = (item) => {
		FlagId.value = item.label;
		if (flagOpotion.value) {
			flagOpotion.value.isOpen = false;
		}
	};

	// 全锁状态
	const disabledSelect3 = () => {
		if (deviceCheckbox.value.length == 1) {
			if (identity.value == false) {
				if (deviceCheckbox.value[0].devKeyLock == 3 || deviceCheckbox.value[0].devKeyLock == 2) {
					uni.showToast({
						title: '设备已锁定，无法操作',
						icon: "none"
					})
					return false
				}
				return true
			}
		} else {
			//  多选
			if (identity.value == false) {
				const hasLock3 = deviceCheckbox.value.some(item => item.devKeyLock == 3);
				// 检查是否有devKeyLock为2的设备
				const hasLock2 = deviceCheckbox.value.some(item => item.devKeyLock == 2);

				if (hasLock3) {
					// 如果有任何设备的devKeyLock为3，则两个都禁用
					uni.showToast({
						title: "设备已锁定，无法操作",
						icon: 'none'
					})
					return false

				} else if (hasLock2) {
					// 如果没有任何设备的devKeyLock为3，但有设备的devKeyLock为2，则只禁用selectDisabled
					uni.showToast({
						title: "设备已锁定，无法操作",
						icon: 'none'
					})
					return false
				} else {
					// 如果既没有3也没有2，则都不禁用
					return true
				}

			}
		}
	}

	// 开放开关机全锁状态
	const disabledSelect2 = () => {
		if (deviceCheckbox.value.length == 1) {
			if (identity.value == false) {
				if (deviceCheckbox.value[0].devKeyLock == 3) {
					uni.showToast({
						title: '设备已锁定，无法操作',
						icon: 'none'
					})
					return false
				}
				return true
			}
		} else {
			//  多选
			if (identity.value == false) {
				const hasLock3 = deviceCheckbox.value.some(item => item.devKeyLock == 3);
				// 检查是否有devKeyLock为2的设备
				const hasLock2 = deviceCheckbox.value.some(item => item.devKeyLock == 2);

				if (hasLock3) {
					// 如果有任何设备的devKeyLock为3，则两个都禁用
					uni.showToast({
						title: "设备已锁定，无法操作",
						icon: 'none'
					})
					return false

				} else {
					return true
				}
			}
		}
	}
	const selectItemLock = (item) => {
		lockId.value = item.label;

		if (lockOpotion.value) {
			lockOpotion.value.isOpen = false;
		}
	};
	const handlerLock = () => {
		if (!disabledSelect3() && identity.value == false) return
		let data = {};
		if (identity.value) {
			data.devKeyLock = ChildLock.value.find(item => item.label == lockId.value)?.value // 管理员网络锁
		} else {
			data.devchildLock = ChildLock.value.find(item => item.label == lockId.value)?.value; // 普通用户童锁
		}
		if (deviceCheckbox.value.length == 1) {

			data.equipNo = deviceCheckbox.value[0].equipNo,
				data.id = deviceCheckbox.value[0].id,
				uni.$u.http.post("/wechat/editSend", data).then((res) => {
					if (res.success) {
						uni.showToast({
							title: "操作成功",
							icon: "success",
						});
					}
					// 先本地更新数据
					deviceCheckbox.value.forEach((item) => {
						const index = deviceList.value.findIndex(
							(device) => device.equipNo === item.equipNo
						);
						if (index !== -1) {
							let updatedItem
							if (identity.value) {
								updatedItem = {
									...deviceList.value[index],
									devKeyLock: Number(ChildLock.value.find(item => item
										.label ==
										lockId.value)?.value),
								};
							} else {
								updatedItem = {
									...deviceList.value[index],
									devchildLock: Number(ChildLock.value.find(item => item
										.label ==
										lockId.value)?.value),
								};
							}
							deviceList.value.splice(index, 1, updatedItem);
						}
					});
					// 重新启动定时器
					startAutoRefresh();
				});
		} else {
			// 多个设备批量控制
			let array = getEquipNoArray(deviceCheckbox.value);

			data.idArray = array,

				nextTick(() => {
					uni.$u.http.post("/wechat/editSendBatchControl", data).then((res) => {
						if (res.success) {
							uni.showToast({
								title: "操作成功",
								icon: "success",
							});
							// 重新启动定时器
							startAutoRefresh();
						}
					});
				});
		}
	};
	const handlerFlag = () => {
		if (!disabledSelect2() && identity.value == false) return;
		let data = {};
		let status = FlagId.value == "开机" ? 1 : 0;
		if (deviceCheckbox.value.length == 1) {
			// 设置单个设备开关机
			data = {
				equipNo: deviceCheckbox.value[0].equipNo,
				devOnOff: status,
				id: deviceCheckbox.value[0].id,
			};
			uni.$u.http.post("/wechat/editSend", data).then((res) => {
				if (res.success) {
					uni.showToast({
						title: "操作成功",
						icon: "success",
					});

					// 先本地更新数据
					deviceCheckbox.value.forEach((item) => {
						const index = deviceList.value.findIndex(
							(device) => device.equipNo === item.equipNo
						);
						if (index !== -1) {
							const updatedItem = {
								...deviceList.value[index],
								devOnOff: status,
								devOnOffName: FlagId.value,
							};
							deviceList.value.splice(index, 1, updatedItem);
						}
					});
					// 重新启动定时器
					startAutoRefresh();
				}
			});
		} else {
			// 多个设备批量控制
			let array = getEquipNoArray(deviceCheckbox.value);
			data = {
				idArray: array,
				devOnOff: status,
			};
			nextTick(() => {
				uni.$u.http.post("/wechat/editSendBatchControl", data).then((res) => {
					if (res.success) {
						uni.showToast({
							title: "操作成功",
							icon: "success",
						});
						// 先本地更新数据
						deviceCheckbox.value.forEach((item) => {
							const index = deviceList.value.findIndex(
								(device) => device.equipNo === item.equipNo
							);
							if (index !== -1) {
								const updatedItem = {
									...deviceList.value[index],
									devOnOff: status,
									devOnOffName: FlagId.value,
								};
								deviceList.value.splice(index, 1, updatedItem);
							}
						});
						// 重新启动定时器
						startAutoRefresh();
					}
				});
			});
		}
	};
	// 设置模式
	const selectItemMode = (item) => {
		modeId.value = item.label;
		if (modeOpotion.value) {
			modeOpotion.value.isOpen = false;
		}
	};
	const handlerMode = () => {
		if (!disabledSelect3() && identity.value == false) return
		let data = {};
		let status = modeList.value.find((obj) => obj.label == modeId.value)?.value;
		if (deviceCheckbox.value.length == 1) {
			// 设置单个模式
			data = {
				equipNo: deviceCheckbox.value[0].equipNo,
				devRunMode: Number(status),
				id: deviceCheckbox.value[0].id,
			};
			uni.$u.http.post("/wechat/editSend", data).then((res) => {
				if (res.success) {
					uni.showToast({
						title: "操作成功",
						icon: "success",
					});
					// 先本地更新数据
					const index = deviceList.value.findIndex(
						(item) => item.equipNo === deviceCheckbox.value[0].equipNo
					);
					if (index !== -1) {
						const updatedItem = {
							...deviceList.value[index],
							devRunMode: Number(status),
						};
						deviceList.value.splice(index, 1, updatedItem);
					}
					// 重新启动定时器
					startAutoRefresh();
				}
			});
		} else {
			// 多个设备批量控制
			let array = getEquipNoArray(deviceCheckbox.value);
			data = {
				idArray: array,
				devRunMode: status,
			};
			nextTick(() => {
				uni.$u.http.post("/wechat/editSendBatchControl", data).then((res) => {
					if (res.success) {
						uni.showToast({
							title: "操作成功",
							icon: "success",
						});
						// 先本地更新数据
						deviceCheckbox.value.forEach((item) => {
							const index = deviceList.value.findIndex(
								(device) => device.equipNo === item.equipNo
							);
							if (index !== -1) {
								const updatedItem = {
									...deviceList.value[index],
									devRunMode: status,
								};
								deviceList.value.splice(index, 1, updatedItem);
							}
						});
						// 重新启动定时器
						startAutoRefresh();
					}
				});
			});
		}
	};

	// 设置温度
	const handlerTempCheck = (item) => {
		tempId.value = item.label;
		if (tempOption.value) {
			tempOption.value.isOpen = false;
		}
	};

	const handerTemp = () => {
		if (!disabledSelect3() && identity.value == false) return
		let data = {};
		let status = Number(tempId.value.replace(/[^0-9.-]/g, ""));
		if (deviceCheckbox.value.length == 1) {
			// 设置单个模式
			data = {
				equipNo: deviceCheckbox.value[0].equipNo,
				devTempset: status,
				id: deviceCheckbox.value[0].id,
			};
			uni.$u.http.post("/wechat/editSend", data).then((res) => {
				if (res.success) {
					uni.showToast({
						title: "操作成功",
						icon: "success",
					});
					getList();
				}
			});
		} else {
			// 多个设备批量控制
			let array = getEquipNoArray(deviceCheckbox.value);
			data = {
				idArray: array,
				devTempset: status,
			};
			nextTick(() => {
				uni.$u.http.post("/wechat/editSendBatchControl", data).then((res) => {
					if (res.success) {
						uni.showToast({
							title: "操作成功",
							icon: "success",
						});
						getList();
					}
				});
			});
		}
	};
	const handlerController = () => {
		if (!disabledSelect3() && identity.value == false) return
		intelligenceShow.value = true
	}
	const handleIntelligenceClose = () => {
		intelligenceShow.value = false
	}
	// 暴露方法给父组件
	defineExpose({
		onContainerClick,
		onPullDownReload,
		handleSearch,
		stopAutoRefresh,
		startAutoRefresh,
		deviceList: deviceList // 暴露 deviceList 给父组件
	});
	// 监听滚动事件，判断是否到达底部
	const onScroll = (e) => {
		// 现在不需要滚动加载了，没有分页了，需要的时候随时打开注释
		// const scrollTop = e.detail.scrollTop // 滚动距离顶部的距离
		// const scrollHeight = e.detail.scrollHeight // 滚动内容总高度
		// const clientHeight = e.detail.clientHeight // 可视区域高度
		// // 当滚动到距离底部200rpx以内，且不在加载中、还有更多数据时，触发加载更多
		// if (
		// 	scrollHeight - scrollTop - clientHeight <= 200 &&
		// 	!loading.value &&
		// 	hasMore.value
		// ) {
		// 	pageNum.value += 1 // 页码+1
		// 	getList() // 加载更多
		// }
	};
</script>

<style lang="scss" scoped>
	@import "./device-component";
</style>
<style lang="scss">
	.option-scroll {
		max-height: 300rpx;
		/* 设置固定高度，根据需要调整 */
		overflow-y: auto;
		-webkit-overflow-scrolling: touch;
		/* 优化iOS滚动体验 */

		/* 自定义滚动条样式（可选） */
		::-webkit-scrollbar {
			width: 4px;
		}

		::-webkit-scrollbar-track {
			background: #f1f1f1;
		}

		::-webkit-scrollbar-thumb {
			background: #c1c1c1;
			border-radius: 4px;
		}
	}

	/* 选项样式 */
	.custom-option {
		border-bottom: 1px solid #eee;
		text-align: center;
		font-size: 26rpx;
		line-height: 50rpx;
	}

	.loading-tip {
		text-align: center;
		padding: 20rpx 0;
		color: #999;
		font-size: 26rpx;
	}
</style>